<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */

namespace app\madmin\service;

use app\madmin\model\ActivityRecharge;
use app\madmin\model\Coupon;
use think\Exception;
use think\facade\Db;
use app\madmin\model\Activity;

class RechargeService
{

    private function buildWhere(array $data)
    {
        $where = ['type' => 1];
        !empty($data['status']) && $where[] = ['status', 'in', $data['status']];
        return $where;
    }

    /**
     * 查询列表
     * @param int $page
     * @param int $size
     * @param array $data
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function index($page = 1, $size = 10, $search = [])
    {
        $list = Activity::where($this->buildWhere($search))->order('status ASC')->paginate(['page' => $page, 'list_rows' => $size]);
        return [HTTP_SUCCESS, $list];
    }

    /**
     * 保存数据
     * @param array $data
     * @return array
     * @throws
     */
    public function save(array $data)
    {
        $check = Activity::check($data);
        try {
            Db::startTrans();
            $activity = Activity::create($check['activity']);
            foreach ($check['rules'] as $key => $value) {
                $activity->recharge()->save($value);
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            throw new Exception($e->getMessage(), HTTP_NOTACCEPT);
        }
        return [HTTP_CREATED, $activity];
    }

    /**
     * 读取一条数据
     * @param int $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function read(int $id)
    {
        $model = Activity::with('recharge')->where(['type' => 1])->find($id);
        if (!empty($model)) {
            foreach ($model->recharge as $key => $value) {
                $coupon = json_decode($value->coupon, true);
                $model->recharge[$key]->coupon = Coupon::where('id', "in", $coupon)->select();
            }
        }
        return [HTTP_SUCCESS, $model];
    }


    /**
     * 更新数据
     * @param int $id
     * @param array $data
     * @return array
     * @throws
     */
    public function update(int $id, array $data)
    {
        $check = Activity::check($data, $id);
        try {
            Db::startTrans();
            Activity::update($check['activity'], ['id' => $id]);
            $ids = array_column(ActivityRecharge::field("id")->where('aid', $id)->select()->toArray(), "id");
            foreach ($check['rules'] as $key => $value) {
                if (isset($value['id'])) {
                    $ids = array_diff($ids, [$value['id']]);
                    ActivityRecharge::update($value, ['id' => $value['id']]);
                } else {
                    $value['aid'] = $id;
                    ActivityRecharge::create($value);
                }
                if (count($ids) > 0) {
                    foreach ($ids as $ik => $iv) {
                        // 删除多余数据
                        ActivityRecharge::destroy($iv);
                    }
                }
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            throw new Exception($e->getMessage(), HTTP_NOTACCEPT);
        }
        return [HTTP_CREATED, "更新成功！"];
    }

    /**
     * @param $id
     * @return array
     * @throws
     */
    public function stop($id)
    {
        try {
            Activity::update([
                'close_time' => date('Y-m-d H:i:s', time()),
                'status' => 2
            ], ['id' => $id]);
            $res = ActivityRecharge::update(['status' => 2], ['aid' => $id]);
        } catch (Exception $e) {
            Db::rollback();
            throw new Exception("发生错误！", HTTP_NOTACCEPT);
        }
        return [HTTP_CREATED, $res];
    }

    /**
     * @param $id
     * @return int
     */
    public function delete($id)
    {
        Activity::update(['status' => 2], ['id' => $id]);
        ActivityRecharge::update(['status' => 2], ['aid' => $id]);
        Activity::destroy($id);
        return HTTP_NOCONTEND;
    }

}
